package com.crcc.common.util;

import java.util.Calendar;

/**
 * 根据身份证号码获取年龄
 *
 * @author zhengxy
 * @since 2021-06-11
 */
public class GetAge {

    // 1971-01-01 08:00:00的时间戳
    private static final long TIME = 31536_000_000L;
    public static String evaluate(String laborIdNum){
        if(laborIdNum == null || "".equals(laborIdNum) ){
            return "身份证件号有误,无法计算年龄";
        }

        if (laborIdNum.length() != 15 && laborIdNum.length() != 18){
            return "身份证件号有误,无法计算年龄";
        }

        String age="身份证件号有误,无法计算年龄";

        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH)+1;
        int dayNow = cal.get(Calendar.DATE);

        int year = Integer.valueOf(laborIdNum.substring(6, 10));
        int month = Integer.valueOf(laborIdNum.substring(10,12));
        int day = Integer.valueOf(laborIdNum.substring(12,14));

        if ((month < monthNow) || (month == monthNow && day<= dayNow) ){
            age = String.valueOf(yearNow - year);
        }else {
            age = String.valueOf(yearNow - year-1);
        }

        return age;
    }
    /**
     * 计算详细年龄，精确到秒
     * @param birth
     * @return
     */
    public static String getAge(String birth){
        if(birth == null || "".equals(birth) ){
            return "出生信息号有误,无法计算年龄";
        }
        try {
            Calendar cal = Calendar.getInstance();
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH)+1;
            int dayNow = cal.get(Calendar.DATE);

            int year = Integer.valueOf(birth.substring(0, 4));
            int month = Integer.valueOf(birth.substring(4,6));
            int day = Integer.valueOf(birth.substring(6,8));

            if ((month < monthNow) || (month == monthNow && day<= dayNow) ){
                return String.valueOf(yearNow - year);
            }else {
                return String.valueOf(yearNow - year-1);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        try {
            System.out.println(getAge("19640306"));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

